import config from '@/static/js/config.js'
import appList from '@/static/js/app.js'
import md5 from './md5.js'
import store from '@/store'

const baseURL = process.env.NODE_ENV === 'development' ? config.dev.BASE_URL : config.env.BASE_URL
// const baseURL = 'http://192.168.110.51:18011'
// const baseURL = 'http://10.168.245.21:18011'
// B0014 绑卡提示需要注册
const exeErrCode = ['B0014', 'C0006']
let APP_CONFIG
export const apiResquest = (prams) => { //prams 为我们需要调用的接口API的参数 下面会贴具体代码
	return new Promise((resolve, reject) => {
		// 获取配置
		if (!APP_CONFIG) {
			let len = appList.length;
			for (let i = 0; i < len; i++) {
				console.log('store.state', store.state.appId, appList[i].APP_ID)
				if (appList[i].APP_ID === store.state.appId) {
					// if (appList[i].APP_ID === '2021004103625029') {
					APP_CONFIG = appList[i].APP_CONFIG
				}
			}
		}
		let url = baseURL + prams.url; //请求的网络地址和局地的api地址组合
		let sign = null;
		console.log(prams.data, Object.keys(JSON.parse(JSON.stringify(prams.data || {}))).length)
		if (prams.data && Object.keys(prams.data).length) {
			// prams.data.appId = APP_CONFIG.APPID;
			sign = transSign(prams.data)
			prams.data.sign = sign;
		} else {
			prams.data = {};
			// prams.data.appId = APP_CONFIG.APPID;
			// sign = transSign(prams.data)
			// prams.data.sign = sign;
		}
		//  else {
		//   prams.data = {}
		//   prams.data.sign = sign
		// }

		return uni.request({
			url: url,
			data: prams.data,
			method: prams.method,
			timeout: 30000,
			// dataType:'text',
			header: {
				'appId': APP_CONFIG.APPID,
				'timestamp': Date.now(),
				'Accept': 'application/json',
				'Content-Type': 'application/json',
				"openId": store.state.userId
			},
			success: (res) => {
				if (res.data.retCode === "T") {
					resolve(res.data.result);
				} else {
					if (exeErrCode.indexOf(res.data.retCode) > -1) {
						reject(res.data);
					} else {
						reject('fail');
						if (res.data.retMsg === undefined) {
							uni.showToast({
								title: res.data.error || res.data.message,
								icon: 'none',
								duration: 2000
							});
						} else {
							uni.showToast({
								title: res.data.retMsg || res.data.message,
								icon: 'none',
								duration: 2000
							});
						}
					}
				}
			},
			fail: (err) => {
				reject('fail');
				// console.log(url,'fail',err)
				uni.showToast({
					title: '系统错误,请稍后重试' + err.errMsg,
					icon: 'none',
					duration: 2000
				});
			},
			complete: () => {
				// console.log('请求完成')
			}
		});
	})
}
// 签名
function transSign(val) {
	function sortArrObj(data) {
		let sortedData = data.map(obj =>
			Object.fromEntries(
				Object.entries(obj).sort(([a], [b]) => a.localeCompare(b))
			)
		);
		return JSON.stringify(sortedData)
	}
	let res = ''
	if (val) {
		let keys = []
		let obj = JSON.parse(JSON.stringify(val))
		keys = Object.keys(obj);
		// console.log(obj, keys)
		keys.sort();
		keys.forEach(item => {
			// console.log(item, typeof(obj[item]), obj[item])
			if (obj[item]) {
				res +=
					`${item}=${typeof(obj[item]) === 'object' ? sortArrObj(obj[item]) : obj[item]}&`
			}

		})
	}
	res += ('appKey=' + APP_CONFIG.APPKEY)
	console.log('sing', res)
	return md5(res)
}